/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using EvalContext = System.Qizx.XQuery.EvalContext;
using Focus = System.Qizx.XQuery.Focus;
using XQType = System.Qizx.XQuery.XQType;
namespace System.Qizx.XQuery.Fn {

    /// <summary>  Implementation of function fn:normalize-space.</summary>
    public class NormalizeSpace : Function {
        public override Prototype[] Protos {
            get {
                return protos;
            }

        }
        internal static Prototype[] protos;

        public static string Normalize(string src) {
            System.Text.StringBuilder buf = new System.Text.StringBuilder();
            bool pendingSpace = false;

            for (int i = 0, L = src.Length; i < L; i++) {
                char c = src[i];
                if (System.Char.IsWhiteSpace(c)) {
                    if (buf.Length > 0)
                        pendingSpace = true;
                } else {
                    if (pendingSpace)
                        buf.Append(' ');
                    buf.Append(c);
                    pendingSpace = false;
                }
            }
            return buf.ToString();
        }


        public class Exec : Function.OptStringCall {
            public override string evalAsOptString(Focus focus, EvalContext context) {
                string src = null;
                if (args.Length == 0) {
                    checkFocus(focus, context);
                    src = focus.currentItem().ValueAsString;
                } else
                    src = args[0].evalAsOptString(focus, context);
                context.at(this);
                return src == null ? "" : System.Qizx.XQuery.Fn.NormalizeSpace.Normalize(src);
            }
        }
        static NormalizeSpace() {
            protos = new Prototype[] { Prototype.fn("normalize-space", XQType.STRING.opt, typeof(Exec)), Prototype.fn("normalize-space", XQType.STRING.opt, typeof(Exec)).arg("srcval", XQType.STRING.opt) };
        }
    }
}